package org.example.sentinel.config;

import com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect;
import com.alibaba.csp.sentinel.init.InitExecutor;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRuleManager;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * 容器启动成功后配置Sentinel规则
 */
@Data
@Slf4j
@Configuration
@ConfigurationProperties(prefix = "sentinel")
public class SentinelConfig implements InitializingBean {
    private List<FlowRule> rules;
    private List<ParamFlowRule> params;

    /**
     * 开启注解
     */
    @Bean
    public SentinelResourceAspect sentinelResourceAspect() {
        return new SentinelResourceAspect();
    }

    /**
     * 加载规则
     */
    public void loadRules() {
        log.info("加载限流规则");
        FlowRuleManager.loadRules(rules);
        ParamFlowRuleManager.loadRules(params);
    }

    @Override
    public void afterPropertiesSet() {
        triggerSentinelInit();
        loadRules();
    }

    /**
     * 触发sentinel初始化。
     */
    private static void triggerSentinelInit() {
        new Thread(InitExecutor::doInit).start();
    }

}
